package com.shuqi.activity;

import java.util.List;

import android.os.Bundle;
import android.os.Handler;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.shuqi.activity.adapter.PayChapterHistoryAdapter;
import com.shuqi.activity.viewport.CommonTitle;
import com.shuqi.activity.viewport.MyListFooter;
import com.shuqi.activity.viewport.MyListFooter.MyFooterListener;
import com.shuqi.common.ControlHandler;
import com.shuqi.common.NetErrorProvider;
import com.shuqi.common.NetErrorProvider.NetErrorListener;
import com.shuqi.controller.MainController;
import com.shuqi.controller.PayChapterHistoryController;
import com.shuqi.controller.R;
import com.shuqi.interfaces.EventTypeConstants;
import com.shuqi.interfaces.IEventListener;
import com.shuqi.model.bean.BuyRecordInfo;
import com.shuqi.model.bean.BuyRecordsInfo;
import com.shuqi.model.net.listener.HttpRequestErrListener;

/**
 * 购入章节Activity
 * 
 * @author zhuchen
 * 
 */
public class PayChapterHistoryActivity extends ActivityBase implements IEventListener, OnClickListener {

    private final int INIT = EventTypeConstants.BASE;
    private final int INITSUCCESS = INIT + 1;
    private final int SHOW404 = INITSUCCESS + 1;
    private final int LOADMORE_ERROR = SHOW404 + 1;

    private PayChapterHistoryController controller;
    private LinearLayout layoutLoading;// 进度圈
    private LinearLayout layoutNoNet;
    private int totalPage; // 总页数
    private int pageIndex = 1;// 请求页
    private String bookId;// 接收的bookId;
    private String chapterTotal;// 接受到的总章节数
    private BuyRecordsInfo buyRecordsInfo;
    private PayChapterHistoryAdapter adapter;
    private ListView mActPaychapterhistoryList;
    private TextView act_chapterTotal;
    private List<BuyRecordInfo> mBuyRecordInfoListData;
    private CommonTitle mTitle;
    private MyListFooter mListFooter;

    private Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case INIT:
                    activityLogicForward();
                    setAllOnListener();
                    break;
                case INITSUCCESS:
                    activityInitData();
                    break;
                case SHOW404:
                    layoutLoading.setVisibility(View.GONE);
                    act_chapterTotal.setVisibility(View.GONE);
                    layoutNoNet.setVisibility(View.VISIBLE);
                    mListFooter.goneLoad();
                    break;
                case LOADMORE_ERROR:
                    layoutLoading.setVisibility(View.GONE);
                    mListFooter.loadingError();
                    break;
                default:
                    break;
            }
        };
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_paychapterhistory);
        if (controller == null) {
            controller =
                    (PayChapterHistoryController) MainController.getMainManagerInstance()
                            .createController(MainController.CONTROLLER_ID_PAYCHAPTERHISTORY, this);
        }
        controller.addEventListener(this);
        bookId = getIntent().getStringExtra("bookId");
        chapterTotal = getIntent().getStringExtra("chapterTotal");
        handler.sendEmptyMessage(INIT);
    }

    @Override
    public void onEvent(int event, Object data) {
        switch (event) {
            case EventTypeConstants.EVENT_SUCCESS:
                this.pageIndex++;
                buyRecordsInfo = (BuyRecordsInfo) data;
                handler.sendEmptyMessage(INITSUCCESS);
                break;
            default:
                if (mBuyRecordInfoListData == null) {
                    handler.sendEmptyMessage(SHOW404);
                } else {
                    handler.sendEmptyMessage(LOADMORE_ERROR);
                }
                break;
        }
    }

    @Override
    public void activityLogicForward() {
        mTitle = (CommonTitle) findViewById(R.id.title);
        mTitle.setLeftClickListener(this);
        mActPaychapterhistoryList = (ListView) findViewById(R.id.act_paychapterhistory_list);
        layoutLoading = (LinearLayout) findViewById(R.id.include_loading);
        layoutNoNet = (LinearLayout) findViewById(R.id.include_error);
        act_chapterTotal = (TextView) findViewById(R.id.act_chapterTotal);
    }

    /** 设置监听事件 */
    private void setAllOnListener() {
        mTitle.setLeftClickListener(this);
        findViewById(R.id.retry).setOnClickListener(this);
        MyFooterListener listener = new MyFooterListener() {

            @Override
            public void reload() {
                requestAppList();
                mListFooter.loadingStart();
            }

            @Override
            public void loadNext() {
                requestAppList();
                mListFooter.loadingStart();
            }

            @Override
            public boolean hasNext() {
                if (mBuyRecordInfoListData == null || mBuyRecordInfoListData.size() == 0) {
                    return false;
                }
                return (totalPage >= pageIndex);
            }

        };
        if(mListFooter == null){
            
            mListFooter = new MyListFooter(this, listener);
            mActPaychapterhistoryList.addFooterView(mListFooter);
        }
        requestAppList();
        mListFooter.loadingStart();
        layoutLoading.setVisibility(View.VISIBLE);
    }

    @Override
    public void activityInitData() {
        layoutLoading.setVisibility(View.GONE);
        layoutNoNet.setVisibility(View.GONE);
        mActPaychapterhistoryList.setVisibility(View.VISIBLE);
        act_chapterTotal.setVisibility(View.VISIBLE);

        // 购买总章节数
        act_chapterTotal.setText("本书已购入："+chapterTotal+"章");
        if (buyRecordsInfo != null && buyRecordsInfo.getList() != null
                && buyRecordsInfo.getList().size() != 0) {
            totalPage = Integer.parseInt(buyRecordsInfo.getTotalPage());

            List<BuyRecordInfo> templist = buyRecordsInfo.getList();
            if (mBuyRecordInfoListData == null) {
                mBuyRecordInfoListData = templist;
            } else {
                mBuyRecordInfoListData.addAll(templist);
            }

            if (adapter == null) {
                adapter = new PayChapterHistoryAdapter(this);
                adapter.setList(mBuyRecordInfoListData);
                mActPaychapterhistoryList.setAdapter(adapter);
            } else {
//                adapter.setList(mBuyRecordInfoListData);
                adapter.notifyDataSetChanged();
            }
            mListFooter.loadingSuccess();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.title_left:
                ActivityManager.getInstance().finishActivity(this);
                break;
            case R.id.retry:
//                if (!Util.isNetworkConnected(this)) {
//                    return;
//                }
//                handler.sendEmptyMessage(INIT);
                NetErrorProvider.getInstance().retry(this, new NetErrorListener() {

                    @Override
                    public void netErrorCallback() {
                        handler.sendEmptyMessage(INIT);

                    }
                });
                break;
            default:
                break;
        }
    }


    /** 翻页加载请求 */
    private void requestAppList() {
        this.controller.handle(0, this.pageIndex, this.bookId); // 获取app数据
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {

            ActivityManager.getInstance().finishActivity(this);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
